import os
import  xml.dom.minidom as xdom

labels = {"knife":0, 
          "scissors":0, 
          "lighter":0, 
          "zippooil":0, 
          "pressure":0, 
          "slingshot":0, 
          "handcuffs":0, 
          "nailpolish":0, 
          "powerbank":0, 
          "firecrackers":0}

def count_label(xml_name):
    '''
    计算一个xml文件中的指定label数
    '''
    # 打开xml文档
    dom = xdom.parse(xml_name)

    # 获得文档元素对象
    xml = dom.documentElement

    # 按名称获取tag列表
    tags = xml.getElementsByTagName('name')

    for tag in tags:
        # print(tag.firstChild.data)
        if tag.firstChild.data in labels.keys():
            labels[tag.firstChild.data] +=1

if __name__ == "__main__":
    # 获取指定目录下的文件名存入列表
    xmls = os.listdir('./xmls')

    # 遍历目录下所有xml文件
    for xml in xmls:
        count_label('./xmls/' + xml)
        print(xml + " has finished reading.")
    print(labels)
